package com.liuchao.maven.practice.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description:
 * @Auther: Liu Chao
 * @Date: 2018/8/11 07:47
 */
public class Receive {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMQUtil.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(Send.QUEUE_NAME, false, false,false, null);
        channel.basicQos(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("[1] receive :" + new String(body));
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(Send.QUEUE_NAME, false, consumer);
    }

    private void old() throws IOException, TimeoutException, InterruptedException {
//        Connection connection = RabbitMQUtil.getConnection();
//        Channel channel = connection.createChannel();
//        QueueingConsumer consumer = new QueueingConsumer(channel);
//        channel.basicConsume(Send.QUEUE_NAME, true, consumer);
//        while (true) {
//            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
//            String msg = new String(delivery.getBody());
//            System.out.println("receive msg: " + msg);
//        }
    }
}
